//
//  BLSelectedList.m
//  ITC_iOS
//
//  Created by iBenz on 2018/9/8.
//  Copyright © 2018年 Benz.L. All rights reserved.
//

#import "BLSelectedList.h"
@interface BLSelectedListTableDelegateObject : NSObject<UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, weak) BLSelectedList *list;
@end

@implementation BLSelectedListTableDelegateObject

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self.list.delegate respondsToSelector:@selector(selectedList:heightForRow:)]?[self.list.delegate selectedList:self.list heightForRow:indexPath.row]:44;
}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.list.delegate respondsToSelector:@selector(numberOfRowsInSelectedList:)]?[self.list.delegate numberOfRowsInSelectedList:self.list]:0;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if ([self.list.delegate respondsToSelector:@selector(selectedList:cellForRow:)]) {
        return [self.list.delegate selectedList:self.list cellForRow:indexPath.row];
    }
    return UITableViewCell.new;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.list.delegate respondsToSelector:@selector(selectedList:didSelectedRow:)]) {
        [self.list.delegate selectedList:self.list didSelectedRow:indexPath.row];
    }
    [self.list hideCompletion:nil];
}

@end

@interface BLSelectedListControl : UIControl
@property(nonatomic, strong) id holder;
@end
@implementation BLSelectedListControl
@end

@interface BLSelectedList()
@property(nonatomic, strong) BLSelectedListTableDelegateObject *delegateObject;
@property(nonatomic, strong) BLSelectedListControl *control;
@property(nonatomic, strong) UIView *cover;
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) UIImageView *arrow;
@property(nonatomic, assign) CGFloat cornerRadius;
@end
@implementation BLSelectedList

- (instancetype)init {
    self = [super init];
    [self initialize];
    return self;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    [self initialize];
}
- (void)initialize {
    _size = (CGSize){80, 140};
    _cornerRadius = 4.0;
}

- (void)dealloc {
    NSLog(@"");
}

#pragma mark - Privates

- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier {
    return [self.tableView dequeueReusableCellWithIdentifier:identifier];
}
- (__kindof BLSelectedListRow *)dequeueReusableCellWithIdentifier:(NSString *)identifier forRow:(NSInteger)row {
    return [self.tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
}
- (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier {
    [self.tableView registerClass:cellClass forCellReuseIdentifier:identifier];
}
- (void)animationWithShow:(BOOL)show completion:(void (^ __nullable)(BOOL finished))completion {
    CGRect frame = self.cover.frame;
    CGFloat height = frame.size.height;
    if (show) {
        frame.size.height = 0.1;
        self.cover.frame = frame;
        [self.control addSubview:self.cover];
    }
    else {
        height = 0.1;
    }
    
    frame.size.height = height;
    [UIView animateWithDuration:0.25 animations:^{
        self.cover.frame = frame;
    } completion:completion];
}

#pragma mark - Getters

- (BLSelectedListTableDelegateObject *)delegateObject {
    if (!_delegateObject) {
        _delegateObject = BLSelectedListTableDelegateObject.new;
        _delegateObject.list = self;
    }
    return _delegateObject;
}

- (CGFloat)heightForRow {
    return 44.0;
}

- (BLSelectedListControl *)control {
    if (!_control) {
        BLSelectedListControl *superView = [[BLSelectedListControl alloc] initWithFrame:UIScreen.mainScreen.bounds];
        [superView addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchDown];
        superView.userInteractionEnabled = YES;
        _control = superView;
    }
    return _control;
}
- (UIView *)cover {
    if (!_cover) {
        _cover = UIView.new;
        _cover.backgroundColor = UIColor.clearColor;
        _cover.layer.masksToBounds = YES;
        [_cover addSubview:self.arrow];
        [_cover addSubview:self.tableView];
    }
    return _cover;
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.layer.masksToBounds = YES;
        _tableView.layer.cornerRadius = _cornerRadius;
        _tableView.delegate = self.delegateObject;
        _tableView.dataSource = self.delegateObject;
        _tableView.tableFooterView = UIView.new;
    }
    return _tableView;
}
- (UIImageView *)arrow {
    if (!_arrow) {
        _arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"下拉框上部"]];
        [_arrow sizeToFit];
    }
    return _arrow;
}

#pragma mark - Public

- (void)reload {
    [self.tableView reloadData];
}

- (void)showWithRelatedView:(UIView *)view completion:(void (^__nullable)(BLSelectedList *list, BOOL finished))completion {
    self.control.holder = self;
    UIWindow *win = UIApplication.sharedApplication.delegate.window;
    [win addSubview:self.control];
    self.control.frame = win.bounds;
    
    CGFloat spaceY = 2.0;
    CGFloat spaceX = 15.0;
    CGRect coverFrame = [self.control convertRect:view.frame fromView:view.superview];
    CGRect frame = self.cover.frame;
    frame.size.width = MIN(self.size.width, self.control.bounds.size.width-spaceX*2);
    frame.size.height = MIN(CGRectGetHeight(self.control.bounds)-CGRectGetMaxY(coverFrame)-spaceY, self.size.height+CGRectGetHeight(self.arrow.bounds));
    frame.origin.y = CGRectGetMaxY(coverFrame)+spaceY;
    frame.origin.x = MAX(spaceX, CGRectGetMinX(coverFrame)+CGRectGetWidth(coverFrame)/2.0-self.size.width/2.0);
    self.cover.frame = frame;
    {
        //更新table的frame
        CGRect tbFrame = self.tableView.frame;
        tbFrame.origin = (CGPoint){0, CGRectGetMaxY(self.arrow.bounds)};
        tbFrame.size = (CGSize){CGRectGetWidth(self.cover.bounds), CGRectGetHeight(self.cover.bounds)-CGRectGetMaxY(tbFrame)};
        self.tableView.frame = tbFrame;
    }
    
    CGFloat xCenter = (CGRectGetMinX(coverFrame)+CGRectGetWidth(coverFrame)/2.0);
    if (xCenter<CGRectGetMinX(frame)+_cornerRadius) {
        xCenter = CGRectGetMinX(frame)+_cornerRadius;
    }
    else if (xCenter>CGRectGetMaxY(frame)-_cornerRadius) {
        xCenter = CGRectGetMaxY(frame)-_cornerRadius;
    }
    CGPoint center = self.arrow.center;
    center.x = xCenter-CGRectGetMinX(frame);
    self.arrow.center = center;
    
    [self animationWithShow:YES completion:^(BOOL finished) {
        [self.tableView reloadData];
        if (completion) {
            completion(self, finished);
        }
    }];
}

- (void)hide {
    [self hideCompletion:nil];
}
- (void)hideCompletion:(void (^__nullable)(BLSelectedList *list, BOOL finished))completion {
    [self animationWithShow:NO completion:^(BOOL finished) {
        [self.control removeFromSuperview];
        if (completion) {
            completion(self, finished);
        }
        self.control.holder = nil;
    }];
}

@end


@implementation BLSelectedListRow
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        if ([self respondsToSelector:@selector(setSeparatorInset:)]){
            self.separatorInset = UIEdgeInsetsZero;
        }
        if ([self respondsToSelector:@selector(setLayoutMargins:)]) {
            self.layoutMargins = UIEdgeInsetsZero;
        }
        //preservesSuperviewLayoutMargins设置为false时，子view不被其父view的LayoutMargin影响
        if ([self respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
            self.preservesSuperviewLayoutMargins = false;
        }
        self.textLabel.textColor = [UIColor darkTextColor];
        self.textLabel.font = [UIFont systemFontOfSize:14];
    }
    return self;
}
@end


